package top.kaoshanji.ch12.synch;

import java.util.Arrays;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * author kaoshanji
 * ^_^
 * create time 2024/11/29 17:01
 */
public class Bank {

    private final double[] accounts;

    // 可重入锁和条件对象是对象的一个属性
    private Lock bankLock;
    private Condition sufficientFunds;

    // 构造器初始化对象属性
    public Bank(int n, double initialBalance) {
        accounts = new double[n];
        Arrays.fill(accounts, initialBalance);

        bankLock = new ReentrantLock();
        sufficientFunds = bankLock.newCondition();
    }

    // 转账...使用了锁和条件变量(标准语法)
    public void transfer(int from, int to, double amount) throws InterruptedException {

        // 获取锁...那么该对象的这么一块代码同一时间只能被一个线程执行
        bankLock.lock();
        try {
            // 首先需要条件满足...如果账户金额小于转换金额，就进行等待
            // 条件等待必须放在while里面，标准写法
            while (accounts[from] < amount) {
                sufficientFunds.await();
            }

            System.out.print(Thread.currentThread());
            accounts[from] -= amount;
            System.out.printf(" %10.2f from %d to %d", amount, from, to);
            accounts[to] += amount;
            System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());

            // 唤醒因为条件不满足而等待的线程
            sufficientFunds.signalAll();

        } finally {
            bankLock.unlock();
        }

    }

    // 该方法被 transfer 调用，里面有个 bankLock 锁
    // 如果线程在 transfer 方法里获得了 bankLock 锁，那么在这里会再次获得..这就是可重入锁
    public double getTotalBalance() {
        bankLock.lock(); // 获得锁，要记得释放

        try {
            double sum = 0;
            for (double a: accounts) {
                sum += a;
            }

            return sum;

        } finally {
            bankLock.unlock();
        }
    }


    // 这个是只读的，而且还是不变的，就不需要同步了
    public int size() {
        return accounts.length;
    }


}
